package com.hx.vending.util;

import com.hx.vending.bean.User;
import com.hx.vending.dao.OnlineOrderMapper;
import com.hx.vending.dao.RefundMapper;
import com.hx.vending.dao.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/12/16.
 */
public class Timer{
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OnlineOrderMapper onlineOrderMapper;
    @Autowired
    private RefundMapper refundMapper;
    /**
     * 每天早上九点运行定时器
     * 统计设置了开启每日收益概况的代理商进行信息推送
     */
    public void userIncomePush()throws Exception{
        System.out.println("---------------------------每早九点定时器触发--------------------");
        User user = new User();
        user.setUserIncomePush("1");
        System.out.println(userMapper);
        //1.查询已经开启了推送功能的代理商
        List<User> userList = userMapper.selectByExample(user);

        String startTime = DateUtil.getLastWeekHours();//昨天凌晨
        String endTime = DateUtil.getWeeHours(0);//当天凌晨

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String time = sdf.format(new Date().getTime() - 24 * 60 * 60 * 1000L);//获取每天九点减去一天时间为昨天

        String message = "每日收益概况:\n总收益:%s元\n线上收益:%s元\n线下收益:%s元\n收益概况日期:%s";

        for(User u:userList){
            //线上总收益
            Double onlineOrderAmount = 0D;
            Map<String,Object> map = onlineOrderMapper.selectOnlineOrderAmount(startTime,endTime,u.getUserId());
            Map<String,Object> refundMap = refundMapper.selectRefundMoneyByTime(startTime,endTime,u.getUserId());
            onlineOrderAmount = BigDecimalUtils.sub(Double.valueOf(map.get("onlineOrderAmount").toString()),
                    Double.parseDouble(refundMap.get("refundMoney").toString()));


            Double underLineAmount = 0D;
            Map<String,Object> underMap = onlineOrderMapper.selectUnderOrder(startTime,endTime,u.getUserId());
            underLineAmount = Double.valueOf(String.valueOf(underMap.get("underLineAmount")));

            Double orderMoney = onlineOrderAmount + underLineAmount;
            if (ToolUtil.isNotEmpty(u) && u.getUserIncomePush().equals("1")){
                //2.1推送到代理商后台中
               PushUtils.getInstance().pushMessage(u.getUserAccount(), String.format(message, orderMoney, onlineOrderAmount, underLineAmount, time));

            }
        }
        System.out.println("---------------------------触发器结束任务-------------------------");
    }
}
